<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users'}">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users'}">用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索区 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="queryInfo.query" placeholder="请输入用户名称" class="input-with-select" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList" />
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-button type="primary" @click="addUserDialog">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区 -->
      <el-row>
        <el-table :data="userList" style="width: 100%" border strip fit>
          <el-table-column type="index" label="序号" width="70" />
          <el-table-column prop="id" label="用户id" width="180" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="mobile" label="手机号码" width="180" />
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="role_name" label="角色" width="180" />
          <el-table-column prop="create_time" label="创建时间" width="180" />
          <el-table-column label="状态" width="180">
            <template v-slot:default="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="userStateChanged(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="380">
            <!-- v-slot:default="scope" -->
            <template v-slot:default="scope">
              <!-- 编辑按钮 -->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserDialog(scope.row.id)">编辑用户</el-button>
              <!-- 分配权限按钮 -->
              <el-button type="danger" icon="el-icon-user-solid" size="mini" @click="setRole(scope.row)">用户权限</el-button>
              <!-- 删除按钮 -->
              <el-button type="warning" icon="el-icon-delete-solid" size="mini" @click="removeUserById(scope.row)">删除用户</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <!-- 分页 -->
      <div class="block">
        <el-pagination
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 5, 10, 20, 50, 100]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加用户对话框 -->
    <!--  :before-close="handleClose" -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="addDialogVisible"
      width="23%"
      :close-on-click-modal="false"
      close-on-press-escape
      show-close
      lock-scroll
      @closed="addDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form ref="userInfoFormRef" :model="userInfoForm" :rules="userInfoFormRules" label-width="100px" class="demo-ruleForm" style="width: 500px;">
        <el-form-item label="用户名称" prop="username">
          <label slot="label">用户名称</label>
          <el-input v-model="userInfoForm.username" placeholder="请输入用户名称" :disabled="!showPassword" />
        </el-form-item>
        <!-- 密码输入框是否显示 -->
        <div v-if="showPassword">
          <el-form-item label="密码" prop="password">
            <label slot="label">密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码</label>
            <el-input v-model="userInfoForm.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="userInfoForm.confirmPassword" placeholder="请输入确认密码" />
          </el-form-item>
        </div>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="userInfoForm.mobile" maxlength="11"	placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <label slot="label">邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱</label>
          <el-input v-model="userInfoForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="addDialogClosed">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色分配权限对话框 -->
    <!--  :before-close="handleClose" -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      close-on-press-escape
      show-close
      lock-scroll
      @closed="setRoleDialogClosed"
    >
      <!-- 内容主体区 -->
      <div>
        <p>当前用户： {{ userInfo.username }}</p>
        <p>当前角色： {{ userInfo.role_name }}</p>
        <p>分配新角色
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </p>
      </div>
      <!-- @node-click="handleNodeClick" -->
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义确认密码验证规则
    var checkConfirmPassword = (rule, value, callback) => {
      if (value !== this.userInfoForm.password) return callback(new Error('两次密码不一致'))
      callback()
    }
    // 自定义手机号码验证规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) return callback()
      callback(new Error('请输入合法的手机号码'))
    }
    // 自定义邮箱验证规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) return callback()
      callback(new Error('请输入合法的邮箱'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userList: [],
      total: 0,
      // 添加用户对话框是否可见
      addDialogVisible: false,
      // 添加编辑对话框标题
      dialogTitle: '',
      // 对话框是否展示密码输入框
      showPassword: true,
      // 添加用户的表单数据
      // 用户对象
      userInfo: {},
      // 所有角色列表
      rolesList: {},
      // 分配角色时，已选中的角色id
      selectedRoleId: '',
      userInfoForm: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      // 分配角色对话框是否可见
      setRoleDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 添加表单的验证规则对象
      userInfoFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在3-20之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '用户名长度在6-16之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { min: 6, max: 16, message: '用户名长度在6-16之间', trigger: 'blur' },
          { validator: checkConfirmPassword }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail }
        ]
      }
    }
  },

  created() {
    this.getUserList()
  },

  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败!')

      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听switch开关用户状态事件
    async userStateChanged(userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('修改用户状态失败！')
      }
      this.$message.success('修改用户状态成功！')
    },
    // 添加用户对话框
    addUserDialog() {
      this.showPassword = true
      this.addDialogVisible = true
      this.dialogTitle = '添加用户'
    },
    // 编辑用户对话框
    async editUserDialog(userId) {
      this.showPassword = false
      this.dialogTitle = '编辑用户'
      const { data: res } = await this.$http.get('users/' + userId)
      if (res.meta.status !== 200) {
        res.mg_state = !res.mg_state
        return this.$message.error('查询用户信息失败！')
      }
      this.userInfoForm = res.data
      this.addDialogVisible = true
    },
    // 关闭Dialog事件,清空所有输入项
    addDialogClosed() {
      this.addDialogVisible = false
      this.$refs.userInfoFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser() {
      console.log(1)
      this.$refs.userInfoFormRef.validate(async valid => {
        if (!valid) return
        // 发起添加用户请求
        delete this.userInfoForm['confirmPassword']

        // 判断是添加用户还是编辑用户
        if (this.showPassword) {
          const { data: res } = await this.$http.post('users', this.userInfoForm)
          // 校验响应状态
          if (res.meta.status !== 201) {
            return this.$message.error('添加用户失败！')
          }
          this.$message.success('添加用户成功！')
          this.addDialogVisible = false
          this.getUserList()
          return
        } else {
          const { data: res } = await this.$http.put('users/' + this.userInfoForm.id, {
            email: this.userInfoForm.email,
            mobile: this.userInfoForm.mobile
          })
          // 校验响应状态
          if (res.meta.status !== 200) {
            return this.$message.error('编辑用户失败！')
          }
          this.$message.success('编辑用户成功！')
          this.addDialogVisible = false
          this.getUserList()
          return
        }
      })
    },
    // 根据id删除用户
    async removeUserById(userInfo) {
      // 弹框询问是否删除
      const confirmResult = await this.$confirm(`确定删除用户【${userInfo.username}】吗？`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'waring'
        // catch捕获点击取消时返回的异常报错
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除！')
      }
      const { data: res } = await this.$http.delete('users/' + userInfo.id)
      // 校验响应状态
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getUserList()
      return
    },
    // 展示分配角色对话框
    async setRole(userInfo) {
      // 在展示对话框前，先获取所有角色
      const { data: res } = await this.$http.get('roles')
      // 校验响应状态
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      // this.$message.success('删除用户成功！')
      this.setRoleDialogVisible = true
      this.rolesList = res.data
      this.userInfo = userInfo
      return
    },
    // 点击按钮，分配角色事件
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择角色！')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role/`, { rid: this.selectedRoleId })
      // 校验响应状态
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}

</script>

<style lang="less" scoped>

</style>
